package com.demo.webflux.simple2;

import java.time.Duration;
import java.util.List;

import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Service;
import org.springframework.web.reactive.function.client.WebClient;

import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

@Service
public class ChatServiceImpl implements ChatService<MessageResponse> {

	private WebClient webClient = WebClient.builder()
			.baseUrl("http://localhost:8085")
			.defaultHeader(HttpHeaders.CONTENT_TYPE, "application/json")
			.defaultHeader(HttpHeaders.ACCEPT, "application/json")
			.build();

	@Override
	public Flux<MessageResponse> getMessageStream() {
		return webClient.get().uri("/getMessageStream")
					.retrieve()
					.bodyToFlux(MessageResponse.class)
					.retryBackoff(Long.MAX_VALUE, Duration.ofMillis(500)); // 在出现错误的情况下进行重试
	}

	@Override
	public Mono<List<MessageResponse>> getMessageAfter(String messageId) {
		return webClient.get().uri("/getMessageAfter")
					.retrieve()
					.bodyToMono(new ParameterizedTypeReference<List<MessageResponse>>() {
					})
					.timeout(Duration.ofSeconds(1))
					.retryBackoff(Long.MAX_VALUE, Duration.ofMillis(500));
	}

}
